package com.stu.controller.student;

import com.stu.context.BaseContext;
import com.stu.pojo.Login;
import com.stu.result.Result;
import com.stu.Dto.StuLoginDto;
import com.stu.serive.LoginService;
import com.stu.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/student")
public class StuLoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public Result login(@RequestBody StuLoginDto login){
        log.info("学生系统登录：{}", login);
        Login e = new Login();
        StuLoginDto stuLoginDto = loginService.stuLogin(login);
        BeanUtils.copyProperties(stuLoginDto,e);
        e.setUsername(stuLoginDto.getStuId());
        //log.info("获取的e:{}",e);
        //登录成功生成令牌，返回令牌
        if(e != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("Id",e.getId());
            claims.put("Name",e.getName());
            claims.put("Username", e.getUsername());
            claims.put("role", 2);
            String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的学生信息
            BaseContext.setRole(2L);
            return Result.success(jwt);
        }
        //生成失败，返回错误信息
        return Result.error("用户名或密码错误");
    }
}
